package com.neuedu.android.helloworld;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.neuedu.android.helloworld.ticket.StationActivity;
import com.neuedu.android.helloworld.ticket.TicketBuy3Activity;

import java.util.Calendar;
import java.util.Date;

public class TicketFragment extends Fragment implements View.OnClickListener {


    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.d("TicketFragment", "=======onAttach=========");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("TicketFragment", "=======onCreate=========");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d("TicketFragment", "=======onCreateView=========");
        return inflater.inflate(R.layout.fragment_ticket, container, false);
    }


    TextView tvStationFrom;
    TextView tvStationTo;
    TextView tvFromStartTime;
    Button button1;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d("TicketFragment", "=======onActivityCreated=========");

        tvStationFrom = getActivity().findViewById(R.id.tvStationFrom);
        tvStationTo = getActivity().findViewById(R.id.tvStationTo);
        ImageView ivOppositeArrows = getActivity().findViewById(R.id.ivOppositeArrows);
        tvFromStartTime = getActivity().findViewById(R.id.tvFromStartTime);
        button1 = getActivity().findViewById(android.R.id.button1);


        ivOppositeArrows.setOnClickListener(this);

        tvFromStartTime.setOnClickListener(this);


        tvStationFrom.setOnClickListener(this);
        tvStationTo.setOnClickListener(this);
        button1.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        //交换站点
        if (v.getId() == R.id.ivOppositeArrows) {
            startTranslate();
        } else if (v.getId() == R.id.tvFromStartTime) {
            selectTime();
        }else if(v.getId() == R.id.tvStationFrom ||  v.getId() == R.id.tvStationTo){
            Intent intent = new Intent(getActivity(), StationActivity.class);
//            getActivity().startActivity(intent);
            getActivity().startActivityForResult(intent,v.getId());
        }else if(v.getId() == android.R.id.button1){
            Intent intent = new Intent(getActivity(), TicketBuy3Activity.class);
            getActivity().startActivity(intent);

            //将查询的出发城市、到达城市记录到SQLite数据库
            logStaion();
        }

    }

    private void logStaion() {

        //打开数据库连接对象
//        SQLiteDatabase db = SQLiteDatabase.create(null);
//        db;//
        int currentVersion = 1;
//        int currentVersion = 2;
        String fileName = "my_station";
        MyStationDataBaseOpenHelper helper = new MyStationDataBaseOpenHelper(getActivity(),fileName,null,currentVersion );
        SQLiteDatabase writeDB = helper.getWritableDatabase();


        //将出发城市、到达城市写入SQLite
        String from =tvStationFrom.getText().toString();
        String to =tvStationTo.getText().toString();
//        writeDB.execSQL("insert into station_log (station_from,station_to) values('"+from+"','"+to+"')");
//        writeDB.execSQL("insert into station_log (station_from,station_to) values(?,? )",   new Object[]{from ,to});

        ContentValues cv = new ContentValues();
        cv.put("station_from",from);
        cv.put("station_to",to);
        writeDB.insert("station_log",null,cv);


//        writeDB.update()
//     delete from station_log where id = ?
//        writeDB.delete("station_log"," id = ?" ,new String[]{"1"});


        writeDB.close();
        helper.close();

    }


    class MyStationDataBaseOpenHelper extends SQLiteOpenHelper {


        public MyStationDataBaseOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        public MyStationDataBaseOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version, @Nullable DatabaseErrorHandler errorHandler) {
            super(context, name, factory, version, errorHandler);
        }

        public MyStationDataBaseOpenHelper(@Nullable Context context, @Nullable String name, int version, @NonNull SQLiteDatabase.OpenParams openParams) {
            super(context, name, version, openParams);
        }

        //初始化的时候
        @Override
        public void onCreate(SQLiteDatabase db) {
            //需要创建表
            db.execSQL("CREATE TABLE \"station_log\" (\n" +
                    "\t\"id\"\tINTEGER PRIMARY KEY AUTOINCREMENT,\n" +
                    "\t\"station_from\"\tTEXT,\n" +
                    "\t\"station_to\"\tTEXT\n" +
                    ")");
        }


        //升级的时候触发
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //根据版本号的变化，不同的版本号，做一些更新、升级的操作（相对数据库）

            Log.d("SQLite","oldVersion: "+oldVersion);
            Log.d("SQLite","newVersion: "+oldVersion);


        }

        /**
         *
         * @param db
         * @param oldVersion
         * @param newVersion
         */
        public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.d("SQLite","oldVersion: "+oldVersion);
            Log.d("SQLite","newVersion: "+oldVersion);
        }
    }








    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        String name = data.getStringExtra("name");
        if (!TextUtils.isEmpty(name)) {
            switch (requestCode) {
                case R.id.tvStationFrom:
                    tvStationFrom.setText(name);
                    break;
                case R.id.tvStationTo:
                    tvStationTo.setText(name);
                    break;
            }
        }


    }
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if(data!= null){
//            String name = data.getStringExtra("name");
//            if(requestCode == R.id.tvStationFrom){
//                tvStationFrom.setText(name);
//            }else if(requestCode == R.id.tvStationTo){
//                tvStationTo.setText(name);
//            }
//        }
//    }

    private void selectTime() {
        //2022/05/30 星期一
        String strTvFromStartTime = tvFromStartTime.getText().toString();
        //2022/05/30
        strTvFromStartTime = strTvFromStartTime.split(" ")[0];
        String[] time = strTvFromStartTime.split("/");
        //time[0] 2022
        //time[1]  5
        //time[2] 30

        //选择出发时间
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                //如果选择 2022年7月20日   year = 2022  month ；6  dayOfMonth 20

                Toast.makeText(getActivity(), "选择的dayOfMonth："+dayOfMonth, Toast.LENGTH_SHORT).show();
                Date selectDate = new Date(year-1900,month,dayOfMonth);
//                    Calendar
                //DateUtils.FORMAT_SHOW_WEEKDAY从日期毫秒对象中获取星期（星期一、星期二、   周一、周二   Monday  Mon 、Tur）
                String weekday = DateUtils.formatDateTime(getActivity(), selectDate.getTime(),
                        DateUtils.FORMAT_SHOW_WEEKDAY|DateUtils.FORMAT_ABBREV_WEEKDAY);

//                    Toast.makeText(getActivity(), "weekday: "+weekday, Toast.LENGTH_SHORT).show();
                Log.d("weekday",weekday);
                //选择日期后，调用此事件
                tvFromStartTime.setText(""+year+"/"+(month+1)+"/"+dayOfMonth+" "+weekday);
            }
        },      Integer.parseInt(time[0]),
                Integer.parseInt(time[1]) - 1,// 月份从0 开始，
                Integer.parseInt(time[2])
        );

        dialog.show();
    }

    private void startTranslate() {
        int duration = 800;
        //启动一个动画
        TranslateAnimation annimationLeft = new TranslateAnimation(0, 220, 0, 0);
        //动画的速度
        annimationLeft.setInterpolator(new DecelerateInterpolator());
        //动画的持续时间
        annimationLeft.setDuration(duration);
        //出发城市 向右移动
        tvStationFrom.startAnimation(annimationLeft);


        //启动一个动画
        TranslateAnimation annimationRight = new TranslateAnimation(0, -220, 0, 0);
        //动画的速度
        annimationRight.setInterpolator(new DecelerateInterpolator());
        //动画的持续时间
        annimationRight.setDuration(duration);

        annimationRight.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            //当动画执行完成，需要交换出发城市、到达城市
            @Override
            public void onAnimationEnd(Animation animation) {
                CharSequence temp = tvStationFrom.getText();
                tvStationFrom.setText(tvStationTo.getText());
                tvStationTo.setText(temp);
            }
        });

        //出发城市 向右移动
        tvStationTo.startAnimation(annimationRight);
    }


    @Override
    public void onStart() {
        super.onStart();
        Log.d("TicketFragment", "=======onStart=========");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("TicketFragment", "=======onResume=========");
    }


    @Override
    public void onPause() {
        super.onPause();
        Log.d("TicketFragment", "=======onPause=========");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d("TicketFragment", "=======onStop=========");

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d("TicketFragment", "=======onDestroyView=========");

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TicketFragment", "=======onDestroy=========");

    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d("TicketFragment", "=======onDetach=========");

    }


}
